<template>
	<div>
		<jk-dialog
			v-model="showDialog"
			:title="`${pageType === 'edit' ? '编辑' : pageType === 'add' ? '新增' : '详情'}-派工单`"
			width="1400px"
			:show-content-loading="showLoading"
			:confirm-btn-loading="confirmBtnLoading"
			:show-confirm-btn="pageType !== 'detail'"
			:show-cancel-btn="pageType !== 'detail'"
			:show-close-btn="pageType === 'detail'"
			@on-close="onVisibleChange(false)"
			@on-cancel="onVisibleChange(false)"
			@on-visible-change="onVisibleChange"
			@on-confirm="onConfirmBtn"
		>
			<el-form
				ref="ruleForm"
				:model="ruleForm"
				:rules="rules"
				label-width="120px"
				:show-message="false"
				:hide-required-asterisk="pageType === 'detail'"
			>
				<div ref="box1">
					<el-tag type="primary" effect="plain" class="margin-bottom-4">
						<span class="el-icon-tickets item-gap"></span>
						<span>基本信息</span>
					</el-tag>
					<jk-card>
						<el-row class="flex-start-center-wrap">
							<el-col :span="8">
								<el-form-item class="margin-bottom-10" label="单据编号">
									<span class="read-only-2">{{ ruleForm.code || '系统自动生成' }}</span>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="margin-bottom-10" label="派工日期" prop="belongDate">
									<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.belongDate }}</span>
									<jk-date-picker v-else v-model="ruleForm.belongDate" size="medium" class="width-100-percent" placeholder="派工日期"></jk-date-picker>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="margin-bottom-10" label="预计完成日期" prop="planCompletionTime">
									<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.planCompletionTime }}</span>
									<jk-date-picker v-else v-model="ruleForm.planCompletionTime" size="medium" type="datetime" class="width-100-percent" placeholder="预计完成日期"></jk-date-picker>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="margin-bottom-10" label="保养类别" prop="upkeepTypeIds">
									<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.upkeepTypeList ? ruleForm.upkeepTypeList.map(x => x.name).join() : '' }}</span>
									<jk-select
										v-else
										v-model="ruleForm.upkeepTypeIds"
										multiple
										:collapse-tags="true"
										:option-list="upkeepTypeList"
										size="medium"
										class="width-100-percent"
										placeholder="保养类别"
										@change="onUpkeepTypeChange"
									></jk-select>
								</el-form-item>
							</el-col>
							<el-col :span="24">
								<el-form-item class="margin-bottom-0" label="备注">
									<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.remark }}</span>
									<el-input v-else v-model="ruleForm.remark" autosize type="textarea" placeholder="备注" />
								</el-form-item>
							</el-col>
						</el-row>
					</jk-card>
				</div>
				<div ref="box2" class="flex-start-center margin-bottom-4 margin-top-10" style="align-items: flex-end;">
					<el-tag v-if="pageType === 'detail'" class="el-icon-tickets" size="mini" type="primary">项目计划</el-tag>
					<jk-button v-else icon="el-icon-plus" size="mini" class="" type="primary" @click="onAddPlanBtn">选择项目计划</jk-button>
				</div>
				<jk-table
					border
					:data="ruleForm.machineList || []"
					:height="dialogTableHeight - 20"
				>
					<vxe-column title="设备名称" align="left" field="machineName" :width="70" />
					<vxe-column title="保养项目及人员" align="left" field="belongDate" :min-width="110">
						<template slot="header">
							<div class="flex-start-center width-100-percent">
								<div style="width: 50px;text-align: center;">序号</div>
								<div style="width: 110px;">项目名称</div>
								<div style="width: 70px;">保养周期</div>
								<div style="width: 140px;">计划保养时间</div>
								<div style="width: 140px;">上次保养时间</div>
								<div style="width: 150px;">保养情况</div>
								<div style="width: 200px;">保养实际开始时间</div>
								<div style="min-width: 150px;flex-grow: 1">人员</div>
								<div style="width: 70px;text-align: center;">操作</div>
							</div>
						</template>
						<template slot-scope="scope">
							<upkeep-order-machine-list
								:machine-index="scope.rowIndex"
								:upkeep-item-list="scope.row.upkeepItemList || []"
								@on-delete-emp-item="onDeleteEmpBtn"
								@on-add-emp="onAddEmpBtn"
								@on-delete-upkeep-item="onDeleteUpkeepItemBtn"
							></upkeep-order-machine-list>
						</template>
					</vxe-column>
				</jk-table>
			</el-form>
		</jk-dialog>
		<selectUpkeepPlanDialog
			:upkeep-type-ids="ruleForm.upkeepTypeIds || []"
			:form-data="ruleForm"
			check-key-name="jobId"
			:checked-data="checkedUpkeepList || []"
			:dialog-state="selectUpkeepPlanDialogState"
			@on-visible-change="onVisibleChangeOfSelectUpkeepPlanDialog"
			@on-confirm="onConfirmBtnOfSelectUpkeepPlanDialog"
		></selectUpkeepPlanDialog>
		<checkboxEmpDialog
			:dialog-state="checkboxEmpDialogState"
			@on-visible-change="onVisibleChangeOfCheckboxEmpDialog"
			@on-confirm="onConfirmBtnOfCheckboxEmpDialog"
		></checkboxEmpDialog>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import { spinProcessPage } from '../../../../api/technology/process';
    import { machineManagerUpkeepTypePage } from '../../../../api/machine/upkeepCategory';
    import { formatDate } from '../../../../utils/jk/jk-tool';
    import selectUpkeepPlanDialog from './components/select-upkeep-plan-dialog';
    import checkboxEmpDialog from './components/checkbox-emp-dialog';
    import {
        machineManagerUpkeepDispatchCreate, machineManagerUpkeepDispatchGet,
        machineManagerUpkeepDispatchUpdate
    } from '../../../../api/machine/upkeepOrder';
    import upkeepOrderMachineList from './components/upkeepOrderMachineList/from-save';
    import { validateArr } from '../../../../utils/jk/validator';
    export default {
        components: {
            upkeepOrderMachineList,
            checkboxEmpDialog,
            selectUpkeepPlanDialog
        },
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            pageType: {
                type: String,
                default: ''
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        mixins: [calHeight],
        data() {
            return {
                checkedUpkeepList: [],
                checkboxEmpDialogState: false,
                selectUpkeepPlanDialogState: false,
                upkeepTypeList: [],
                processList: [],
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                ruleForm: {
                    'belongDate': '',
                    'code': '',
                    'machineList': [],
                    'remark': '',
                    'auditState': 0,
                    'planCompletionTime': '',
                    'upkeepTypeIds': [],
                    'upkeepTypeList': []
                },
                rules: {
                    upkeepTypeIds: [{ required: true, validator: validateArr, trigger: 'change' }],
                    code: [{ required: true, trigger: 'change' }],
                    belongDate: [{ required: true, trigger: 'change' }],
                    name: [{ required: true, trigger: 'change' }],
                    processId: [{ required: true, trigger: 'change' }],
                    cycleMax: [{ required: true, trigger: 'change' }],
                    cycleMin: [{ required: true, trigger: 'change' }]
                },
                rawMachine: [],
                machineIndex: null,
                upkeepIndex: null
            };
        },
        methods: {
            onUpkeepTypeChange() {
                this.filterAndSortList();
            },
            onDeleteUpkeepItemBtn(machineIndex, upkeepIndex) {
                this.ruleForm.machineList[machineIndex].upkeepItemList.splice(upkeepIndex, 1);
                if (!this.ruleForm.machineList[machineIndex].upkeepItemList.length) {
                    this.ruleForm.machineList.splice(machineIndex, 1);
                }
            },
            onDeleteEmpBtn(machineIndex, upkeepIndex, empIndex) {
                this.ruleForm.machineList[machineIndex].upkeepItemList[upkeepIndex].empList.splice(empIndex, 1);
            },
            onAddEmpBtn(machineIndex, upkeepIndex) {
                this.machineIndex = machineIndex;
                this.upkeepIndex = upkeepIndex;
                this.checkboxEmpDialogState = true;
            },
            onVisibleChangeOfCheckboxEmpDialog(e) {
                this.checkboxEmpDialogState = e;
            },
            onConfirmBtnOfCheckboxEmpDialog(arr) {
                if (arr) {
                    arr.forEach(x => {
                        this.ruleForm.machineList[this.machineIndex].upkeepItemList[this.upkeepIndex].empList.push({
                            empId: x.id,
                            empCode: x.code,
                            empName: x.name
                        });
                    });
                    this.checkboxEmpDialogState = false;
                }
            },
            onAddPlanBtn() {
                this.checkedUpkeepList = [];
                this.ruleForm.machineList.forEach(x => {
                    x.upkeepItemList.forEach(k => {
                        this.checkedUpkeepList.push(k);
                    });
                });
                this.selectUpkeepPlanDialogState = true;
            },
            // 格式化项目计划的字段
            formatUpkeepItemInfo(x) {
                return {
                    jobId: x.id,
                    upkeepItemName: x.upkeepItemName,
                    lastUpkeepTime: x.lastUpkeepTime,
                    planUpkeepTime: x.planUpkeepTime,
                    upkeepTypeId: x.upkeepTypeId,
                    upkeepTypeCode: x.upkeepTypeCode,
                    upkeepTypeName: x.upkeepTypeName,
                    cycleUnit: x.cycleUnit,
                    cycleMin: x.cycleMin,
                    cycleMax: x.cycleMax,
                    sortNum: x.sortNum,
                    empList: x.optionalEmpList || []
                };
            },
            onConfirmBtnOfSelectUpkeepPlanDialog(arr = []) {
                arr.forEach(x => {
                    const machineIds = this.ruleForm.machineList ? this.ruleForm.machineList.map(x => x.machineId) : [];
                    if (machineIds.includes(x.machineId)) {
                        this.ruleForm.machineList.forEach(machineItem => {
                            if (x.machineId === machineItem.machineId) {
                                machineItem.upkeepItemList.push(this.formatUpkeepItemInfo(x));
                            }
                        });
                    } else {
                        this.ruleForm.machineList.push({
                            machineId: x.machineId,
                            machineCode: x.machineCode,
                            machineName: x.machineName,
                            upkeepItemList: [this.formatUpkeepItemInfo(x)]
                        });
                    }
                });
                this.filterAndSortList();
                this.selectUpkeepPlanDialogState = false;
            },
            // 根据保养类别过滤并对项目计划进行排序
            filterAndSortList() {
                let list = [];
                this.ruleForm.machineList.forEach(x => {
                    if (this.ruleForm.upkeepTypeIds) {
                        list = x.upkeepItemList ? x.upkeepItemList.filter(k => this.ruleForm.upkeepTypeIds.includes(k.upkeepTypeId)) : [];
                    } else {
                        list = x.upkeepItemList ? x.upkeepItemList : [];
                    }
                    this.$set(x, 'upkeepItemList', list.sort((a, b) => {
                        return a.sortNum - b.sortNum;
                    }));
                });
                this.ruleForm.machineList = this.ruleForm.machineList.filter(x => x.upkeepItemList && x.upkeepItemList.length);
            },
            onVisibleChangeOfSelectUpkeepPlanDialog(e) {
                this.selectUpkeepPlanDialogState = e;
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                params.upkeepTypeList = params.upkeepTypeIds ? this.upkeepTypeList.filter(x => params.upkeepTypeIds.includes(x.id)) : [];

                return params;
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        const api = !this.dataId ? machineManagerUpkeepDispatchCreate : machineManagerUpkeepDispatchUpdate;
                        this.confirmBtnLoading = true;
                        api(this.getParamData()).then(res => {
                            this.confirmBtnLoading = false;
                            if (res.data.status === 200) {
                                this.$tipsBar(this, 'save');
                                this.$emit('on-finish');
                            }
                        });
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return machineManagerUpkeepDispatchGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        resData.upkeepTypeIds = resData.upkeepTypeList ? resData.upkeepTypeList.map(x => x.id) : [];
                        this.ruleForm = resData;
                    }
                });
            },
            getProcessListRequest() {
                return spinProcessPage({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.processList = res.data.res || [];
                    }
                });
            },
            getUpkeepTypeListRequest() {
                return machineManagerUpkeepTypePage({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.upkeepTypeList = res.data.res ? res.data.res.map(x => {
                            return {
                                id: x.id,
                                code: x.code,
                                name: x.name
                            };
                        }) : [];
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                await this.getUpkeepTypeListRequest();
                await this.getProcessListRequest();
                if (!this.dataId) {
                    this.$set(this.ruleForm, 'belongDate', formatDate(Date.now()));
                }
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
